//全量实现undo和redo

class UndoRedoManager {
    constructor(canvas, collaborationRef) {
        this.canvas = canvas;
        this.collaborationRef = collaborationRef;
        this.undoStack = [];
        this.redoStack = [];
        this.isRestoringState = false;
        this.isUndoRedoOperation = false;

        // 初始化时保存初始状态
        this.saveInitialState();
    }
    setCollaboration(collaboration) {
        this.collaborationRef = collaboration;
    }
    // 保存初始状态
    saveInitialState() {
        if (!this.canvas) return;
        const initialState = this._getFilteredCanvasState();
        this.undoStack.push(initialState);
    }

    // 保存当前状态
    saveState() {
        // 忽略临时操作和状态恢复时的保存
        if (this.isRestoringState || this.isUndoRedoOperation) {
            console.log('忽略状态保存：正在恢复状态或执行撤销/重做操作');
            return;
        }

        try {
            const currentState = this._getFilteredCanvasState();

            // 检查新状态是否与栈顶状态相同
            const lastState = this.undoStack[this.undoStack.length - 1];
            if (lastState && JSON.stringify(currentState) === JSON.stringify(lastState)) {
                console.log('状态未变化，不保存');
                return;
            }

            // 如果状态不同，说明有真实变化，直接保存
            this.undoStack.push(currentState);
            console.log('currentState+++++++++++++++', currentState);
            this.redoStack = []; // 清空重做栈

            // 添加更详细的日志
            console.log('状态已保存', {
                undo: this.undoStack.length,
                redo: this.redoStack.length
            });
        } catch (error) {
            console.error('保存状态时出错:', error);
        }
    }

    // 获取过滤后的画布状态（不包含光标）
    _getFilteredCanvasState() {
        // 获取所有对象
        const objects = this.canvas.getObjects();

        // 过滤掉光标对象
        const filteredObjects = objects.filter(
            (obj) => obj.type !== 'cursor' && !obj.id?.includes('cursor')
        );

        // 临时保存当前的objects
        const originalObjects = this.canvas._objects;

        // 临时替换为过滤后的objects
        this.canvas._objects = filteredObjects;

        // 获取JSON状态
        const state = this.canvas.toJSON(['id']);

        // 恢复原始objects
        this.canvas._objects = originalObjects;

        return state;
    }

    // 应用状态到画布
    async _applyState(state) {
        try {
            this.isRestoringState = true;
            this.isUndoRedoOperation = true;

            // 清空当前画布
            this.canvas.clear();

            // 如果状态为空，直接返回
            if (!state) return;
            // 如果有对象，加载对象
            if (state.objects && state.objects.length > 0) {
                await this.canvas.loadFromJSON(state, () => {
                    this.canvas.requestRenderAll();

                    // 以state为准同步sharedObjects
                    if (this.collaborationRef?.sharedObjects) {
                        const sharedObjects = this.collaborationRef.sharedObjects;

                        // 遍历state中的对象，更新或添加
                        state.objects.forEach((obj) => {
                            if (obj.id && obj.type !== 'cursor') {
                                const serializedObj = JSON.stringify({
                                    id: obj.id,
                                    type: obj.type || 'unknown',
                                    objData: obj,
                                    timestamp: Date.now(),
                                    userId: this.collaborationRef?.current?.userId
                                });
                                sharedObjects.set(obj.id, serializedObj);
                            }
                        });

                        // 删除state中不存在的对象
                        sharedObjects.forEach((_, key) => {
                            const exists = state.objects.some((obj) => obj.id === key);
                            if (!exists) {
                                sharedObjects.delete(key);
                            }
                        });
                    }
                });
            }
        } catch (error) {
            console.error('应用状态时出错:', error);
        } finally {
            this.isRestoringState = false;
            this.isUndoRedoOperation = false;
        }
    }

    // 广播撤销/重做操作
    _broadcastUndoRedo(action, state) {
        if (this.collaborationRef) {
            // 广播状态和栈信息
            console.log('state+++++++++++++++', state);
            this.collaborationRef.broadcastUndoRedoCommand(`command:${action}`, {
                state,
                stackInfo: {
                    undoStack: this.undoStack,
                    redoStack: this.redoStack
                }
            });
        }
    }

    // 处理远程撤销/重做操作
    async handleRemoteUndoRedo(action, data) {
        try {
            this.isUndoRedoOperation = true;
            this.isRestoringState = true;
            console.log('data.state+++++++++++++++', data.state);
            // debugger;
            await this._applyState(data.state);
            // 同步栈状态
            if (data.stackInfo) {
                this.undoStack = [...data.stackInfo.undoStack];
                this.redoStack = [...data.stackInfo.redoStack];
            }

            // 应用新状态

            console.log(`远程${action}操作已应用`, {
                undo: this.undoStack.length,
                redo: this.redoStack.length
            });
        } catch (error) {
            console.error(`处理远程${action}操作时出错:`, error);
        } finally {
            this.isRestoringState = false;
            this.isUndoRedoOperation = false;
        }
    }

    // 撤销操作
    async undo() {
        if (this.undoStack.length <= 1) {
            console.log('无法撤销：没有更多历史状态');
            return false;
        }

        try {
            this.isUndoRedoOperation = true;
            const currentState = this.undoStack.pop();
            if (currentState) {
                this.redoStack.push(currentState);
            }

            const previousState = this.undoStack[this.undoStack.length - 1];

            await this._applyState(previousState);

            // 广播新状态和栈信息
            this._broadcastUndoRedo('undo', previousState);

            console.log('撤销操作 - 完成', {
                undo: this.undoStack.length,
                redo: this.redoStack.length
            });

            return true;
        } catch (error) {
            console.error('撤销操作时出错:', error);
            return false;
        } finally {
            this.isUndoRedoOperation = false;
        }
    }

    // 重做操作
    async redo() {
        if (this.redoStack.length === 0) {
            console.log('无法重做：没有被撤销的操作');
            return false;
        }

        try {
            this.isUndoRedoOperation = true;
            const nextState = this.redoStack.pop();
            if (!nextState) {
                console.error('无效的重做状态');
                return false;
            }

            this.undoStack.push(nextState);
            await this._applyState(nextState);

            // 广播新状态和栈信息
            this._broadcastUndoRedo('redo', nextState);

            console.log('重做操作 - 完成', {
                undo: this.undoStack.length,
                redo: this.redoStack.length
            });

            return true;
        } catch (error) {
            console.error('重做操作时出错:', error);
            return false;
        } finally {
            this.isUndoRedoOperation = false;
        }
    }

    // 清空历史记录
    clearHistory() {
        this.undoStack = [];
        this.redoStack = [];
        this.saveInitialState();
        console.log('历史记录已清空', {
            undo: this.undoStack.length,
            redo: this.redoStack.length
        });
    }
}

export default UndoRedoManager;
